<template>
  <a-space>
    <selectMultiple :key="selMulData.key" :info="selMulData" :defaultVal="selMulData.value" @change="selectMulVal($event, selMulData)" />

    <a-select v-model="searchValue.matchType" :style="{ width: '160px' }" allow-clear placeholder="请选择">
      <a-option value="NEGATIVE_EXACT">否定精确</a-option>
      <a-option value="NEGATIVE_PHRASE">否定词组</a-option>
    </a-select>

    <filterKeywordByType ref="FilterKeywordByType" :currentItem="keyWordSearchType" @search="selectMulVal($event, keyWordSearchType, 'hasSearchType')" />

    <a-range-picker v-model="searchValue.time" :style="{ width: 300 + 'px' }" :allow-clear="false" shortcuts-position="left" :shortcuts="rangeShortcuts()" />
    <a-button class="gray-outline" @click="search">搜索</a-button>
  </a-space>

  <div>
    <a-space class="mt5">
      <a-button class="gray-outline" size="medium" v-if="$authPass('negativeKeyword.adjust')" @click="changeStatus('ARCHIVED')">归档</a-button>
      <a-button type="primary" size="medium" v-if="$authPass('negativeKeyword.create')" @click="addNegativeKeyword">新增否定</a-button>
    </a-space>
  </div>

  <a-table class="mt5 table-two-line" row-key="id" :loading="tableLoading" size="mini" :row-selection="{ type: 'checkbox', showCheckedAll: true, onlyCurrent: false }" v-model:selectedKeys="ids" :pagination="false" :data="tableDate" :scroll="{ y: '300px', x: '100%' }">
    <template #columns>
      <a-table-column :width="160" data-index="keywordText" title="否定关键词" />
      <a-table-column :width="70" title="否定状态">
        <template #cell="{ record }">
          <p :class="$extract(statusMap[record.state], 'color')">{{ $extract(statusMap[record.state], 'name') }}</p>
        </template>
      </a-table-column>
      <a-table-column :width="80" title="匹配类型">
        <template #cell="{ record }">
          <p>{{ NegativeKeywordMatchType[record.matchType] || record.matchType }} </p>
        </template>
      </a-table-column>
      <a-table-column :width="140" title="创建时间" data-index="creationDateTime">
        <template #cell="{ record }">
          <p>{{ $setTime(record.creationDateTime) }}</p>
        </template>
      </a-table-column>
      <a-table-column :width="60" title="操作">
        <template #cell="{ record }">
          <a-popconfirm v-if="$authPass('negativeKeyword.adjust')" content="确定是否归档该否定关键词" @ok="requestUpdataState([record], 'ARCHIVED')" type="warning">
            <a-button v-if="record.state != 'ARCHIVED'" type="text">归档</a-button>
          </a-popconfirm>
        </template>
      </a-table-column>
    </template>
  </a-table>

  <div class="pagination-footer mt10">
    <a-pagination size="mini" :total="pagination.total" :default-page-size="pagination.pageSize" :current="pagination.pageNum" :page-size-options="[20, 50, 100, 200, 300]" show-total show-page-size @page-size-change="sizeChange" @change="changePage" />
  </div>

  <!-- 添加否定关键词 -->
  <AddNegativeKeyword v-if="showAddNegativeKeyword" :info="props.info" :level="props.info.currentLevel" type="add" :isShow="showAddNegativeKeyword" :defaultVal="defaultVal" @closed="showAddNegativeKeyword = false" @success="getTableList" />
</template>

<script lang="ts" setup>
  import { computed, ref, reactive, onMounted } from 'vue'
  import { rangeShortcuts, getStartAndEndTime } from '../../../common'
  import { AdStatusHandle, NegativeKeywordMatchType } from '../../../types'
  import { negativeKeywordList, adjustNegativeKeyword } from '@/api/advert'
  import { Message, Modal } from '@arco-design/web-vue'
  import selectMultiple from '@/components/Form/selectMultiple.vue'
  import AddNegativeKeyword from './addNegativeKeyword.vue'
  import filterKeywordByType from '@/components/Form/filterKeywordByType.vue'
  const props = defineProps(['info'])
  const FilterKeywordByType = ref()
  const statusMap = {
    ENABLED: { name: '已开启', color: 'normal' },
    PAUSED: { name: '已暂停', color: 'normal' },
    ARCHIVED: { name: '已归档', color: 'gray' },
  }
  let pagination = ref({ total: 0, pageSize: 20, pageNum: 1 })
  let tableLoading = ref(false)
  let showAddNegativeKeyword = ref(false)
  let submitLoading = ref(false)
  let tableDate = ref([])
  let ids = ref([])
  let defaultVal = ref()

  let selMulData: any = ref({
    key: 'states',
    label: '状态',
    value: ref(['ENABLED']),
    type: 'select_multiple',
    width: 180,
    optionItems: [
      {
        label: '投放中',
        value: 'ENABLED',
      },
      {
        label: '已暂停',
        value: 'PAUSED',
      },
      {
        label: '已归档',
        value: 'ARCHIVED',
      },
    ],
  })

  let keyWordSearchType = ref({
    type: 'input_keyword_type',
    key: 'keywordText',
    keyItems: [{ label: '否定关键词', value: 'keywordText' }],
    keyWidth: '120',
    value: ref(),
    placeholder: '请输入',
    label: '',
    width: 160,
    isMultiple: false,
  })

  let searchValue: any = ref({
    matchType: '',
    time: getStartAndEndTime('last_30_days'),
    orderItems: null,
  })

  const search = () => {
    let obj = FilterKeywordByType.value.selInfo
    searchValue.value.keywordText = obj.value
    searchValue.value.keywordIsTheSearchAccurate = obj.searchType == 'exact' ? true : false
    getTableList()
  }

  const sizeChange = (val: number) => {
    pagination.value.pageNum = 1
    pagination.value.pageSize = val
    getTableList()
  }
  const changePage = (val: number) => {
    pagination.value.pageNum = val
    getTableList()
  }

  const selectMulVal = (searchVal: any, item: any, type?: string) => {
    console.log(searchVal, 'searchVal')

    if (type) {
      keyWordSearchType.value.value = searchVal.value
    } else {
      item.value = searchVal
    }

    search()
  }

  const getTableList = async () => {
    let params = {
      ...searchValue.value,
      campaignId: [props.info.campaignId],
      pageNum: pagination.value.pageNum,
      pageSize: pagination.value.pageSize,
      startDate: searchValue.value.time[0],
      endDate: searchValue.value.time[1],
    }

    tableLoading.value = true
    const res: any = await negativeKeywordList(params)
    tableLoading.value = false
    if (res) {
      pagination.value.total = res?.data?.total
      tableDate.value = res.data.data || []
      tableDate.value.forEach((el: any) => {
        el.id = el.shopId + el.campaignId + el.keywordId
      })
    }
  }

  // 批量修改否定关键词状态
  function changeStatus(status: any) {
    if (!ids.value.length) {
      return Message.error('请选择否定关键词')
    }
    Modal.confirm({
      title: '调整状态',
      content: `请再次确认，是否${AdStatusHandle[status]}选中的否定关键词`,
      cancelText: '取消',
      okText: '确认',
      onOk: async () => {
        let arr = <Array<any>>[]
        ids.value.forEach((el: any) => {
          let item = tableDate.value.find((e: any) => e.shopId + e.campaignId + e.keywordId == el)
          if (item) arr.push(item)
        })
        requestUpdataState(arr, status, AdStatusHandle[status] + '成功')
      },
    })
  }

  //归档否定关键词状态请求
  async function requestUpdataState(list: Array<any>, state: string, msg?: string) {
    let params = list.map((el: any) => {
      return {
        keywordId: el.keywordId,
        adType: el.adType,
        shopId: el.shopId,
      }
    })
    submitLoading.value = true
    const res: any = await adjustNegativeKeyword(params)
    submitLoading.value = false
    if (!res) return
    getTableList()
    if (msg) {
      Message.success(msg)
    }
  }

  function addNegativeKeyword() {
    defaultVal.value = ''
    showAddNegativeKeyword.value = true
  }

  onMounted(() => {
    getTableList()
  })
</script>

<style lang="less" scoped></style>
